import 'package:easy_refresh/easy_refresh.dart';
import 'package:get/get.dart';
import 'package:wan_android_flutter/common/base/base_controller.dart';
import 'package:wan_android_flutter/common/network/model/tutorials_model.dart';

import '../../common/network/http_util.dart';
import '../../common/network/json_parse.dart';
import '../../common/network/model/categorys_model.dart';
import 'tutorial_state.dart';

class TutorialLogic extends BaseController {
  final TutorialState state = TutorialState();

  EasyRefreshController controller = EasyRefreshController(
    controlFinishRefresh: true,
    controlFinishLoad: true,
  );

  @override
  void onInit() {
    super.onInit();
    if (Get.arguments is Category) {
      state.category = Get.arguments;
      state.title.value = state.category.chapterName ?? "";
    }
  }

  @override
  Future<void> onLoadData() async {
    super.onLoadData();
    loadTutorials();
  }

  Future<void> loadTutorials() async {
    final response = await httpUtil
        .get("/article/list/${state.pageIndex}/json?cid=${state.category.chapterId}&order_type=0");
    if (response.statusCode == 200 && response.data is Map<String, dynamic>) {
      final tutorialsModel = JsonParse.fromJsonMap<TutorialsModel>(response.data);
      if (tutorialsModel?.data?.datas?.isNotEmpty == true) {
        if (state.pageIndex == 0) {
          state.tutorialList.assignAll(tutorialsModel!.data!.datas!);
        } else {
          state.tutorialList.addAll(tutorialsModel!.data!.datas!);
        }
        state.tutorials.assignAll(state.tutorialList);
        controller.finishRefresh();
        controller.finishLoad();
      }
    }
  }
}
